package com.javaee.thinks.tools;

import com.javaee.thinks.po.ConversationHistory;
import okhttp3.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit; // 导入 TimeUnit

public class Thinker {
    static BufferedReader br;

    static {
        try {
            br = new BufferedReader(new FileReader("C:\\Users\\23619\\Desktop\\tools\\api\\googleApi.txt"));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    static String apiToken;

    static {
        try {
            apiToken = br.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static SqlSessionFactory sqlSessionFactory;
    private static final ConnectionPool connectionPool = new ConnectionPool(5, 5, TimeUnit.MINUTES); //连接池

    static { // 静态初始化块
        try {
            Reader reader = Resources.getResourceAsReader("config/mybatis_config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException("Failed to create SqlSessionFactory", e);
        }
    }

    // 111111111111111111111.不带记忆的对话 (单参数 prompt)
    public static String chat_nonmemory(String prompt) {
        return chat_nonmemory(prompt, null);
    }

    // 222222222222222222222.不带记忆的对话 (prompt 和 )
    public static String chat_nonmemory(String prompt, String conversationName) {
        // --- 1. 从数据库加载对话历史 (如果 conversationName 不为 null 或空) ---
        List<ConversationHistory> history = new ArrayList<>();
        if (conversationName != null && !conversationName.trim().isEmpty()) {
            try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
                history = sqlSession.selectList("com.javaee.thinks.po.ConversationHistory.getConversationHistory", conversationName);
            } catch (Exception e) {
                throw new RuntimeException("Error loading conversation history from database", e);
            }
        } // 如果 conversationName 为 null 或空，history 列表保持为空，表示没有历史记录

        // --- 2. 准备 API 请求 ---
        String API_ENDPOINT = null;
            API_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=" + apiToken;
        // OkHttpClient client = new OkHttpClient();  // 原始的, 没设置超时
        // 修改部分开始：创建 OkHttpClient 并设置超时
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(120, TimeUnit.SECONDS) // 连接超时：120秒
                .readTimeout(120, TimeUnit.SECONDS)    // 读取超时：120秒
                .writeTimeout(120, TimeUnit.SECONDS)   // 写入超时：120秒
                .connectionPool(connectionPool) //连接池
                .build();
        // 修改部分结束

        MediaType mediaType = MediaType.parse("application/json");

        // --- 3. 构建 JSON 请求体 ---
        JSONArray contents = new JSONArray();

        // 添加历史对话 (如果存在)
        try {
            for (ConversationHistory conversation : history) {
                JSONObject contentObj = new JSONObject();
                contentObj.put("role", conversation.getRole());
                JSONArray partsArray = new JSONArray();
                JSONObject partObj = new JSONObject();
                String timestampStr = conversation.getTimestamp() != null
                        ? conversation.getTimestamp().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                        : "Unknown Time";
                partObj.put("text", conversation.getMessage() + " 时间：" + timestampStr);

                partsArray.put(partObj);
                contentObj.put("parts", partsArray);
                contents.put(contentObj);
            }

            // 添加当前的用户输入 (prompt)
            LocalDateTime now_pre = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String now = "此信息发出时间：" + now_pre.format(formatter);

            JSONObject userContent = new JSONObject();
            userContent.put("role", "user");
            JSONArray userParts = new JSONArray();
            userParts.put(new JSONObject().put("text", prompt + " " + now+"全程请保持中文对话"));
            userContent.put("parts", userParts);
            contents.put(userContent);

        } catch (JSONException e) {
            throw new RuntimeException("Error constructing JSON request body", e);
        }

        RequestBody body;
        try {
            body = RequestBody.create(mediaType, new JSONObject().put("contents", contents).toString());
        } catch (JSONException e) {
            throw new RuntimeException("Error creating request body", e);
        }

        // --- 4. 构建并发送请求 ---
        Request request = new Request.Builder()
                .url(API_ENDPOINT)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();

        // --- 5. 处理响应 ---
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                return "Error: API request failed. Status Code: " + response.code() + "\nResponse Body:\n" + response.body().string();
            } else {
                String jsonResponse = response.body().string();
                JSONObject responseJsonObject = new JSONObject(jsonResponse);
                JSONArray candidates = responseJsonObject.getJSONArray("candidates");
                JSONObject firstCandidate = candidates.getJSONObject(0);
                JSONObject content = firstCandidate.getJSONObject("content");
                JSONArray parts = content.getJSONArray("parts");
                JSONObject firstPart = parts.getJSONObject(0);
                String modelResponse = firstPart.getString("text");
                return modelResponse;
            }
        } catch (IOException | JSONException e) {
            throw new RuntimeException("Error during API call or JSON processing", e);
        }
    }

    // 3333333333333333333333333333333333333333333.带记忆的对话 (prompt 和 conversationName)
    public static String chat(String prompt, String conversationName) {
        // --- 1.  处理 conversationName ---
        // 如果 conversationName 为 null 或空，则生成一个默认的 ID
        String effectiveConversationId = conversationName;
        if (effectiveConversationId == null || effectiveConversationId.trim().isEmpty()) {
            effectiveConversationId = "conversation_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        }

        // --- 2. 从数据库加载/创建对话历史 ---
        List<ConversationHistory> history = new ArrayList<>();
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            history = sqlSession.selectList("com.javaee.thinks.po.ConversationHistory.getConversationHistory", effectiveConversationId);


            // --- 3. 准备 API 请求 ---
            String API_ENDPOINT = null;
                API_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=" +apiToken;


            //OkHttpClient client = new OkHttpClient();
            // 修改部分开始：创建 OkHttpClient 并设置超时
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(120, TimeUnit.SECONDS) // 连接超时：120秒
                    .readTimeout(120, TimeUnit.SECONDS)    // 读取超时：120秒
                    .writeTimeout(120, TimeUnit.SECONDS)   // 写入超时：120秒
                    .connectionPool(connectionPool)
                    .build();
            // 修改部分结束

            MediaType mediaType = MediaType.parse("application/json");

            // --- 4. 构建 JSON 请求体 ---
            JSONArray contents = new JSONArray();

            // 添加历史对话
            for (ConversationHistory conversation : history) {
                JSONObject contentObj = new JSONObject();
                contentObj.put("role", conversation.getRole());
                JSONArray partsArray = new JSONArray();
                JSONObject partObj = new JSONObject();
                String timestampStr = conversation.getTimestamp() != null
                        ? conversation.getTimestamp().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
                        : "Unknown Time";
                partObj.put("text", conversation.getMessage() + " 时间：" + timestampStr);

                partsArray.put(partObj);
                contentObj.put("parts", partsArray);
                contents.put(contentObj);
            }

            // 添加当前的用户输入 (prompt)
            LocalDateTime now_pre = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String now = "此信息发出时间：" + now_pre.format(formatter);

            JSONObject userContent = new JSONObject();
            userContent.put("role", "user");
            JSONArray userParts = new JSONArray();
            userParts.put(new JSONObject().put("text", prompt + " " + now+"全程请保持中文对话"));
            userContent.put("parts", userParts);
            contents.put(userContent);

            // --- 5. 构建并发送请求 ---
            RequestBody body;
            try {
                body = RequestBody.create(mediaType, new JSONObject().put("contents", contents).toString());
            } catch (JSONException e) {
                throw new RuntimeException("Error creating request body", e);
            }
            Request request = new Request.Builder()
                    .url(API_ENDPOINT)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // --- 6. 处理响应并保存到数据库 ---
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    return "Error: API request failed. Status Code: " + response.code() + "\nResponse Body:\n" + response.body().string();
                } else {
                    String jsonResponse = response.body().string();
                    JSONObject responseJsonObject = new JSONObject(jsonResponse);
                    JSONArray candidates = responseJsonObject.getJSONArray("candidates");
                    JSONObject firstCandidate = candidates.getJSONObject(0);
                    JSONObject content = firstCandidate.getJSONObject("content");
                    JSONArray parts = content.getJSONArray("parts");
                    JSONObject firstPart = parts.getJSONObject(0);
                    String modelResponse = firstPart.getString("text");

                    // 将用户输入和模型回复保存到数据库
                    ConversationHistory userEntry = new ConversationHistory(effectiveConversationId, "user", prompt);
                    ConversationHistory modelEntry = new ConversationHistory(effectiveConversationId, "model", modelResponse);
                    sqlSession.insert("com.javaee.thinks.po.ConversationHistory.insertConversation", userEntry);
                    sqlSession.insert("com.javaee.thinks.po.ConversationHistory.insertConversation", modelEntry);
                    sqlSession.commit(); // 提交事务

                    return modelResponse;
                }
            } catch (IOException | JSONException e) {
                throw new RuntimeException("Error during API call or JSON processing", e);
            }
        } catch (Exception e) {
            throw new RuntimeException("Error interacting with the database", e);
        }
    }
    public static void deleteHistoryByName(String conversationName) {
        try {
            SqlSessionFactory sqlSessionFactory;
            Reader reader = Resources.getResourceAsReader("config/mybatis_config.xml"); // 替换为你的配置文件路径
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.delete("com.javaee.thinks.po.ConversationHistory.clearConversationHistory", conversationName);
            sqlSession.commit();
            sqlSession.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}